package com.iqik.rpc.client;

import com.iqik.rpc.handler.UserHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    // 1。创建一个线程池对象， --处理自定义时间
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // 2。声明自定义事件处理器
    private static UserHandler userHandler = null;
    private static NioEventLoopGroup group;
    private static Bootstrap bootstrap;
    public static ChannelFuture channel;
    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public ChannelFuture getChannel() {
        return channel;
    }

    // 3。编写方法，初始化客户端
    public void init() throws InterruptedException {
        // 初始化UserHandler
        userHandler = new UserHandler();
        // 创建连接池对象
        group = new NioEventLoopGroup();
        // 创建客户端的引导类对象
        bootstrap = new Bootstrap();

        // 配置启动引导类对象
        bootstrap.group(group)
                // 设置通道为NIO
                .channel(NioSocketChannel.class)
                // 设置请求为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                // 监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        // 添加自定义时间处理器
                        pipeline.addLast(userHandler);
                    }
                });

        // 连接服务端
        channel = bootstrap.connect(host, port).sync();
    }

    public void stop() throws Exception {
        if (channel.isSuccess()) {
            if (channel.channel().isActive()) {
                channel.channel().close().sync();
            }
            group.shutdownGracefully().sync();
        }
    }

    /**
     * 4。使用JDK动态代理创建对象
     * @param serviceClass  接口类型，根据那个接口生成子类代理对象，
     * @param providerParam "UserService#sayHello# "
     * @return
     */
    public Object createProxy(Class<?> serviceClass, final String providerParam) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 初始化客户端client
                        if (userHandler == null) {
                            init();
                        }
                        // 给UserClientHandler 设置param
                        userHandler.setParam(providerParam + args[0]);
                        // 使用线程池 开启一个线程处理call(), 写操作, 并返回结果
                        Object result = executorService.submit(userHandler).get();
                        // 返回结果
                        return result;
                    }
                });
    }
}
